﻿//Object扩展
var ObjectUtility = {
    getPropertyValue: function (obj, key) {
        if (key == undefined || key == "") {
            return obj;
        }
        var value;
        var index = key.indexOf('.')
        if (index != -1) {
            var objnext = obj[key.substr(0, index)];
            var next = key.substr(index + 1);
            value = this.getPropertyValue(objnext, next);
        } else {
            value = obj[key];
        }
        return value;
    },
    //属性值覆盖，而不新增属性
    SetValueFromTarget: function (self, target) {
        for (var i in self) {
            var v = target[i];
            if (v != undefined) {
                self[i] = v;
            }
        }
        return self;
    },
    isArray: function (obj) {
        return obj && obj.constructor == Array;
    },
    isFunction: function (obj) {
        return obj &&  obj.constructor == Function;
    },
    isString: function (obj) {
        return obj && obj.constructor == String;
    },
    isNumber: function (obj) {
        return obj && obj.constructor == Number;
    },
    isBoolean: function (obj) {
        return obj && obj.constructor == Boolean;
    },
    EquesTo: function (x, y) { //比较两个对象是否相等，属性比较
        if (x == y) {
            return true;
        }
        if (!(x instanceof Object) || !(y instanceof Object)) {
            return false;
        }
        if (x.constructor !== y.constructor) {
            return false;
        }

        for (var p in x) {
            if (x.hasOwnProperty(p)) {
                if (!y.hasOwnProperty(p)) {
                    return false;
                }
                if (x[p] === y[p]) {
                    continue;
                }
                if (typeof (x[p]) !== "object") {
                    return false;
                }
                if (!ObjectUtility.EquesTo(x[p], y[p])) {
                    return false;
                }
            }
        }

        for (p in y) {
            if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
                return false;
            }
        }
        return true;
    },
    Clone: function (obj) {
        var z = JSON.stringify(obj);
        return JSON.parse(z);
    },
    //将json字符串转化为url字符串拼接
    GetJsonUrl: function (obj) {
        var url = '&';
        for (var i in obj) {
            url += i + "=" + encodeURIComponent(obj[i]) + '&';
        }
        return url;
    },
    //获取json的key  {"A":"B"} 获取A
    GetJsonKey: function (obj) {
        for (var i in obj) {
            return i;
        }
    },
    //获取json的Value  {"A":"B"} 获取B
    GetJsonValue: function (obj) {
        for (var i in obj) {
            return obj[i];
        }
    },
};
//Array扩展
var ArrayUtility = {
    //映射  返回JSON数组 ArrayUtility.Map(array, {"姓名":"Name","学校":"School.Name"})
    //映射  返回普通数组 ArrayUtility.Map(array, "Name")
    Map: function (arr, mapJson) {
        if (arr == null) {
            return [];
        }
        var reArray = [];
        if (typeof (mapJson) == typeof ([])) {
            for (var i = 0; i < arr.length; i++) {
                var model = new Object();
                for (var j in mapJson) {
                    var valueObj = mapJson[j];
                    model[j] = ObjectUtility.getPropertyValue(arr[i], valueObj);
                }
                reArray.push(model);
            }
        } else {
            for (var i = 0; i < arr.length; i++) {
                var v = ObjectUtility.getPropertyValue(arr[i], mapJson);
                reArray.push(v);
            }
        }

        return reArray;
    },
    Select: function (arr) {
        //var d = myList.Select("Age", "Class.Name", function (d) {
        //    return d.Age * 10;
        //}, "MaxAge"); 
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            var model = new Object();
            for (var j = 0; j < arguments.length; j++) {
                var colName = arguments[j];
                if (ObjectUtility.isString(colName)) {
                    var index = colName.indexOf(".");
                    if (index != -1) {
                        colName = colName.substr(index + 1);
                    }
                    model[colName] = ObjectUtility.getPropertyValue(arr[i], arguments[j]);
                } else if (ObjectUtility.isFunction(colName)) {
                    model[arguments[j + 1]] = arguments[j](arr[i]);
                    j++;
                }

            }
            reArray.push(model);
        }
        return reArray;
    },

    Where: function (arr, func) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (func(arr[i])) {
                reArray.push(arr[i]);
            }
        }
        return reArray;
    },
    WhereStr: function (arr, Expre) {
        var reArray = [];
        var index = -1;
        var compairArray = ['=', '>', '<', '>=', '<=', '!='];
        var splitStr = '';
        for (var i = 0; i < compairArray.length; i++) {
            index = Expre.indexOf(compairArray[i]);
            if (index != -1) {
                splitStr = compairArray[i];
                break;
            }
        }
        if (index == -1) {
            alert(Expre + "未分析到运算符,程序将终止！");
            return;
        }

        var left = Expre.substr(0, index);
        var rightValue = Expre.substr(index + 1);

        for (var i = 0; i < arr.length; i++) {
            var leftValue = ObjectUtility.getPropertyValue(arr[i], left);
            if (leftValue != undefined) {
                if (ObjectUtility.isString(rightValue)) {
                    leftValue = "'" + leftValue + "'";
                }
                if (eval(leftValue + splitStr + rightValue)) {
                    reArray.push(arr[i]);
                }
            }
        }
        return reArray;
    },
    Skip: function (arr, len) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (len <= i) {
                reArray.push(arr[i]);
            }
        }
        return reArray;
    },
    Take: function (arr, len) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (len > i) {
                reArray.push(arr[i]);
            }
        }
        return reArray;
    },
    OrderBy: function (arry, field, isDesc) {
        var asc = isDesc == undefined;
        for (var i = 0; i < arry.length - 1; i++) {
            for (var j = 0; j < arry.length - 1 - i; j++) {
                var pre = ObjectUtility.getPropertyValue(arry[j], field);
                var now = ObjectUtility.getPropertyValue(arry[j + 1], field);
                var ischange = pre > now;
                if (!isNaN(pre) || !isNaN(now)) {
                    if (asc) {
                        ischange = parseFloat(pre) > parseFloat(now);
                    } else {
                        ischange = parseFloat(pre) < parseFloat(now);
                    }
                }
                if (ischange) {
                    var temp = arry[j];
                    arry[j] = arry[j + 1];
                    arry[j + 1] = temp;
                }
            }
        }
        return arry;
    },
    OrderByDesc: function (arry, field) {
        return this.OrderBy(arry, field, false);
    },
    Distinct: function (arr) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            var isExist = false;
            for (var j = 0; j < reArray.length; j++) {
                if (ObjectUtility.EquesTo(reArray[j], arr[i])) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                reArray.push(arr[i]);
            }
        }
        return reArray;
    },
    DistinctFieldList: function (arr, fieldName) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            var value = ObjectUtility.getPropertyValue(arr[i], fieldName);
            if (!this.Contains(reArray, value)) {
                reArray.push(value);
            }
        }
        return reArray;
    },
    SingleOrDefault: function (arr, func) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (func(arr[i])) {
                return arr[i];
            }
        }
        return null;
    },
    FirstOrDefault: function (arr) {
        return arr.length != 0 ? arr[0] : null;
    },
    LastOrDefault: function (arr) {
        return arr.length != 0 ? arr[arr.length - 1] : null;
    },
    RemoveByValue: function (arry, name, value) {
        //name=value的被移除 
        var reArray = [];
        for (var i = 0; i < arry.length; i++) {
            var val = ObjectUtility.getPropertyValue(arry[i], name);
            if (val != value) {
                reArray.push(arry[i]);
            }
        }
        return reArray;
    },
    Del: function (arr, func) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (!func(arr[i])) {
                reArray.push(arr[i]);
            }
        }
        return reArray;
    },
    LeftJoinTable: function (arry, leftTable, func) {
        var reArray = [];
        for (var i = 0; i < arry.length; i++) {
            var val = ObjectUtility.getPropertyValue(arry[i], name);
            if (val != value) {
                reArray.push(arry[i]);
            }
        }
        return reArray;
    },
    Contains: function (arr, value) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return true;
            }
        }
        return false;
    },
    Any: function (arr, func) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (func(arr[i])) {
                return true;
            }
        }
        return false;
    },
    //依据属性分组支持School.Name级联属性
    GroupBy: function (array, field) {
        var groupArr = [];
        for (var i = 0; i < array.length; i++) {
            var obj = array[i];
            var objValue = ObjectUtility.getPropertyValue(obj, field);
            if (!this.Any(groupArr, function (d) {
                return d.Name == objValue;
            })) {
                var groupModel = {
                    Name: objValue
                };
                groupArr.push(groupModel);
                var childArray = this.Where(array, function (d) {
                    return ObjectUtility.getPropertyValue(d, field) == objValue;
                }) || [];
                groupModel.Childs = childArray;
            }
        }
        return groupArr;
    },
    //获取所在的索引
    GetIndex: function (arr, func) {
        var reArray = [];
        for (var i = 0; i < arr.length; i++) {
            if (func(arr[i])) {
                return i;
            }
        }
        return null;
    },

    //获取最大的属性
    Max: function (arr, field) {
        var max = 0;
        for (var i = 0; i < arr.length; i++) {
            try {
                var v = parseFloat(arr[i][field]);
                if (v > max) {
                    max = v;
                }
            } catch (e) {

            }
        }
        return max;
    },
};
//String扩展
var StringUtil = {
    FormatDate: function (obj, format) {
        return new Date(obj).Format(format);
    },
    startWith: function (mainStr, subStr) {
        if (mainStr == null || mainStr == undefined) {
            return false;
        }
        mainStr = mainStr + '';
        return mainStr.indexOf(subStr) == 0;
    },
    endWith: function (mainStr, subStr) {
        if (mainStr == null || mainStr == undefined || mainStr.length < subStr) {
            return false;
        }
        var workstr = mainStr.substr(mainStr.length - subStr.length);
        return workstr == subStr;
    },
    ltrim: function (mainStr, str) {
        if (mainStr == null || mainStr == undefined) {
            return false;
        }
        mainStr = mainStr + '';
        str = str || " ";
        if (this.startWith(mainStr, str)) {
            mainStr = mainStr.substr(str.length, mainStr.length - str.length);
        }
        return mainStr;
    },
    rtrim: function (mainStr, str) {
        if (mainStr == null || mainStr == undefined) {
            return false;
        }
        mainStr = mainStr + '';
        str = str || " ";
        if (this.endWith(mainStr, str)) {
            mainStr = mainStr.substr(0, mainStr.length - str.length);
        }
        return mainStr;
    },
    trim: function (mainStr, str) {
        mainStr = this.ltrim(mainStr, str);
        mainStr = this.rtrim(mainStr, str);
        return mainStr;
    },
    Length: function (mainStr) {
        if (mainStr == null || mainStr == undefined) {
            return 0;
        }
        mainStr = mainStr + '';
        return mainStr.replace(/[\u0391-\uFFE5]/g, "aa").length;
    },
    cutStr: function (mainStr, strLen, replaceStr) {
        if (mainStr == null || mainStr == undefined) {
            return "";
        }
        mainStr = mainStr + '';

        replaceStr = replaceStr || "...";
        if (this.Length(mainStr) <= strLen)
            return mainStr;
        var returnStr = "";
        var tempLen = 0;
        for (var i = 0; i < mainStr.length; i++) {
            var tempChar = mainStr[i].match(/[^\x00-\xff]/ig);
            returnStr += mainStr[i];
            tempLen += tempChar == null ? 1 : 2;
            if (tempLen >= strLen) {
                return i + 1 < mainStr.length ? returnStr + replaceStr : returnStr;
            }
        }
        return "";
    },
    //1：含左  2：含右  3：含左右  0：不包含
    SearchValue: function (mainstr, startStr, endStr, flag) {
        var startIndex = mainstr.indexOf(startStr);
        var endIndex = (endStr == undefined || endStr == "") ? mainstr.length : mainstr.indexOf(endStr);

        mainstr = mainstr.substr(startIndex + startStr.length, endIndex - startIndex - startStr.length);
        var containFlag = flag || 0;
        if (containFlag == 1) {
            return startStr + mainstr;
        }
        if (containFlag == 2) {
            return mainstr + endStr;
        }
        if (containFlag == 3) {
            return startStr + mainstr + endStr;
        }
        return mainstr;
    },
    //字符串替换函数
    replaceAll: function (str, oldstr, newstr, isIgnoreCase = true) {
        if (str == null || str == '' ||
            oldstr == null || oldstr == '' ||
            newstr == null ||
            str.indexOf(oldstr) == -1) {
            return str;
        }
        var pushStr = ''; //返回的替换后的新字符串
        var workStr = str; //匹配窗口字符串  oldstr为滑动窗口字符串

        var next = true; //指示是否进行下一轮匹配 
        while (next) {
            for (var b = 0; b < workStr.length; b++) {
                var startSuccess = (isIgnoreCase ? workStr[b].toLowerCase() == oldstr[0].toLowerCase() : workStr[b] == oldstr[0]);
                var AllSuccess = false;
                if (startSuccess) {
                    if (oldstr.length == 1) {
                        AllSuccess = true;
                    } else {
                        for (var oldStrIndex = 1; oldStrIndex < oldstr.length; oldStrIndex++) {
                            var workStrIndex = b + oldStrIndex;
                            AllSuccess = (isIgnoreCase ? workStr[workStrIndex].toLowerCase() == oldstr[oldStrIndex].toLowerCase() :
                                workStr[workStrIndex] == oldstr[oldStrIndex]);
                            if (!AllSuccess) {
                                break;
                            }
                        }
                    }
                }
                if (AllSuccess) {
                    pushStr += workStr.substr(0, b) + newstr;
                    workStr = workStr.substr(b + oldstr.length);
                    break;
                }
            }
            next = isIgnoreCase ? workStr.toLowerCase().indexOf(oldstr.toLowerCase()) >= 0 : workStr.indexOf(oldstr) >= 0;
        }
        pushStr += workStr;
        return pushStr;
    },
    format: function (mainStr) {
        if (arguments.length == 0)
            return null;
        var str = mainStr;
        for (var i = 1; i < arguments.length; i++) {
            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
            str = str.replace(re, arguments[i]);
        }
        return str;
    },
    join: function (arry, popeName, char = ',') {
        var str = "";
        if (!ObjectUtility.isArray(arry)) {
            for (var i = 0; i < arry.length; i++) {
                str += arry[i] + char;
            }
        }
        for (var i = 0; i < arry.length; i++) {
            str += ObjectUtility.getPropertyValue(arry[i], popeName) + char;
        }
        str = this.rtrim(str, char);
        return str;
    },
    IsNullEmptyOrSpace: function (mainStr) {
        if (mainStr == null) return true;
        return mainStr.replace(/s/g, '').length == 0;
    },
    //删除所有的HTML标签
    TrimAllHtml: function (mainStr) {
        var dd = mainStr.replace(/<\/?.+?>/g, "");
        var dds = dd.replace(/ /g, ""); //dds为得到后的内容
        dds = StringUtil.replaceAll(dds, '&nbsp;', '');
        return dds;
    },
    addOrUpdateUrlPara: function (mainStr, key, value) {
        return URLUtility.addOrUpdateUrlPara(key, value, mainStr);
    }
};
var CookieUtil = {
    GetCookie: function (name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) {
            return unescape(arr[2]);
        } else {
            return null;
        }
    },
    SetCookie: function (name, value, time) {
        var exp = new Date();
        exp.setMinutes(exp.getMinutes() + time);
        document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
    },
    delCookie: function (name) {
        var exp = new Date();
        exp.setMinutes(exp.getMinutes() - 1);
        var cval = this.GetCookie(name);
        if (cval != null)
            document.cookie = name + "=" + cval + ";path=/;expires=" + exp.toGMTString();
    },
    delAllCookies: function () {
        var ca = document.cookie.split(';');

        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            var name = c.split('=')[0];
            this.delCookie(name);
        }
    }
};
//LocalStrorage
var LocalUtil = {
    Save: function (name, value) {
        if (typeof (value) == "object") {
            localStorage.setItem(name, JSON.stringify(value));
        } else {
            localStorage.setItem(name, value);
        }
    },
    Get: function (name) {
        var value = localStorage.getItem(name);
        if (value == undefined) {
            return '';
        }
        if (value[0] == '{' || value[0] == '[') {
            var v = JSON.parse(value);
            return v;
        }
        return value;

    },
    Del: function (name) {
        localStorage.removeItem(name);
    },
};
//日期扩展
DateTimeUtility = {
    /*获取日期差几天
var day = GetDateDiff("2016-10-11", new Date().toLocaleDateString(), "day");
alert(day);*/
    getDateDiff: function (startTime, endTime, diffType) {
        diffType = diffType || "day";
        startTime = startTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        diffType = diffType.toLowerCase();
        var sTime = new Date(startTime); //开始时间
        var eTime = new Date(endTime); //结束时间
        //作为除数的数字
        var divNum = 1;
        switch (diffType) {
            case "second":
                divNum = 1000;
                break;
            case "minute":
                divNum = 1000 * 60;
                break;
            case "hour":
                divNum = 1000 * 3600;
                break;
            case "day":
                divNum = 1000 * 3600 * 24;
                break;
            default:
                break;
        }
        return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
    },

    formatDateTimeStyle: function (dates, format) {
        if (!dates) {
            return "";
        }
        if (typeof dates === "string") {
            // 解决IOS上无法从dateStr parse 到Date类型问题
            dates = dates.replace(/-/g, '/');
        }

        format = format || "yyyy-MM-dd hh:mm:ss";
        var date = new Date(dates);
        var o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(), //day
            "h+": date.getHours(), //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
            "S": date.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    },
    toShortDate: function (date) {
        return DateTimeUtility.formatDateTimeStyle(date, 'yyyy-MM-dd');
    },
    toLongDate: function (date) {
        return DateTimeUtility.formatDateTimeStyle(date, 'yyyy-MM-dd hh:mm:ss');
    },

    //格式化JS格式日期 数字形式转为普通形式
    formatNumberTime: function (val, formateDateStyle) {
        var re = /-?\d+/;
        var m = re.exec(val);
        var d = new Date(parseInt(m[0]));
        var formatStyle = formateDateStyle || "yyyy-MM-dd hh:mm:ss";
        return this.formatDateTimeStyle(new Date(d), formatStyle);
    },

    //获取前时间，
    getCurrentDateTime: function (formatStyle) {
        return this.formatDateTimeStyle(new Date(), formatStyle);
    },

    //加减天数
    addDate: function (offset, date) {
        date = date || new Date();
        var d = new Date(date);

        d.setDate(d.getDate() + offset);
        return this.formatDateTimeStyle(d);
    },

    addMonth: function (offset, date) {
        date = date || new Date();
        var d = new Date(date);

        d.setMonth(d.getMonth() + offset);
        return this.formatDateTimeStyle(d);
    },

    addHour: function (offset, date) {
        date = date || new Date();
        var d = new Date(date);

        d.setHours(d.getHours() + offset);
        return this.formatDateTimeStyle(d);
    },

    addMinutes: function (offset, date) {
        date = date || new Date();
        var d = new Date(date);

        d.getMinutes(d.setMinutes() + offset);
        return this.formatDateTimeStyle(d);
    },

    addSeconds: function (offset, date) {
        date = date || new Date();
        var d = new Date(date);

        d.setSeconds(d.getSeconds() + offset);
        return this.formatDateTimeStyle(d);
    },

    //扩展
    //获取某月最小的一天
    getMonthMinDay: function (formatStyle) {
        formatStyle = formatStyle || "yyyy-MM-01";
        return this.formatDateTimeStyle(new Date(), formatStyle);
    },
    getMonthMaxDay: function (formatStyle) {
        formatStyle = formatStyle || "yyyy-MM-dd";
        var cur = DateTimeUtility.getMonthMinDay();
        var next = DateTimeUtility.addMonth(1, cur);
        next = DateTimeUtility.addDate(-1, next);

        return this.formatDateTimeStyle(next, formatStyle);
    },
    //获取时间，兼容IOS
    getDateTime: function (d) {
        if (d == undefined) {
            return new Date(new Date().toString().replace(/-/g, '/'));
        }
        return new Date(d.replace(/-/g, '/'));
    }
}
//文件扩展
FileUtility = {
    getFileValidExt: function (fileId, validExtList) {
        var obj = document.getElementById(fileId);
        photoExt = obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase(); //获得文件后缀名
        var valid = false;
        for (var i = 0; i < validExtList.length; i++) {
            var ext = validExtList[i].toLowerCase();
            if (ext == photoExt) {
                valid = true;
                break;
            }
        }
        return valid;
    },
    //获取文件名
    getFileName: function (FileId) {
        var fileName = document.getElementById(FileId).files[0].name;
        return fileName;
    },
    //获取文件大小 返回MB fileId 2位小数
    getFileSize: function (fileId) {
        try {
            var obj = document.getElementById(fileId);
            var fileSize = 0;
            var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
            if (isIE && !obj.files) {
                var filePath = obj.value;
                var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                var file = fileSystem.GetFile(filePath);
                fileSize = file.Size;
            } else {
                fileSize = obj.files[0].size;
            }
            fileSize = Math.round((fileSize / (1024 * 1024)) * 100) / 100;
            return fileSize;

        } catch (e) {

        }
        return 0;
    }
}
//URL参数扩展
URLUtility = {
    //无参''
    getUrlParam: function (name, defaultValue, orignalUrl) {
        var list = this.getUrlKeyValueArray(orignalUrl);
        if (list != null && list.length != 0) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].Key.toLowerCase() == name.toLowerCase()) {
                    return decodeURI(list[i].Value);
                }
            }
        }
        return defaultValue == undefined ? '' : defaultValue;
    },

    //获取URL 参数列表 Key Value List
    getUrlKeyValueArray: function (orignalUrl) {
        var list = [];
        var url = orignalUrl || document.URL;
        if (url.indexOf('#') >= 0) {
            url = url.substr(0, url.length - 1);
        }
        var paraArray = url.substring(url.indexOf("?") + 1, url.length).split("&");

        for (var i = 0; i < paraArray.length; i++) {
            var workPara = paraArray[i].replace(eval("/" + " " + "/g"), "");
            var index = workPara.indexOf('=');
            var key = workPara.substring(0, index);
            if (key.length == 0) {
                continue;
            }
            var value = workPara.substring(index + 1, workPara.length);

            var pair = new Object();
            pair.Key = key;
            pair.Value = value;

            var isAdd = true;
            for (var j = 0; j < list.length; j++) {
                var obj = list[j];
                if (obj.Key.toLowerCase() == key.toLowerCase()) {
                    obj.Value = obj.Value + "," + value;
                    isAdd = false;
                }
            }

            if (isAdd) {
                list.push(pair);
            }
        }
        return list;
    },

    //获取URL 参数对象
    getUrlKeyValueObjet: function (orignalUrl) {
        var list = {};
        var url = orignalUrl || document.URL;
        var paraArray = url.substring(url.indexOf("?") + 1, url.length).split("&");

        for (var i = 0; i < paraArray.length; i++) {
            var workPara = paraArray[i].replace(eval("/" + " " + "/g"), "");
            var index = workPara.indexOf('=');
            var key = workPara.substring(0, index);
            if (key.length == 0) {
                continue;
            }
            var value = workPara.substring(index + 1, workPara.length);

            list[key] = value;
        }
        return list;
    },
    ///获取URLJSON
    GetUrlJson: function (url) {
        var arry = this.getUrlKeyValueArray(url);
        var params = new Object();
        for (var i = 0; i < arry.length; i++) {
            params[arry[i].Key] = arry[i].Value;
        }
        return params;
    },

    ///获取URL参数
    GetUrl: function () {
        var url = window.location.href;
        var dz_url = url.split('#')[0];
        var cs = dz_url.split('?')[1];
        if (cs) {
            var cs_arr = cs.split('&');
            var cs = {};
            for (var i = 0; i < cs_arr.length; i++) {
                cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
            }
        } else {

        }
        return cs;

    },

    addOrUpdateUrlPara: function (key, value, orignalUrl) {
        /// <summary>
        ///更新URL信息
        /// </summary>
        /// <param name="para">Key</param>
        /// <param name="value">值</param>
        /// <param name="orignalUrl">原始URL</param>
        /// <returns>返回替换成功的URL</returns>
        orignalUrl = orignalUrl || document.URL;
        var domainUrl = orignalUrl;
        if (orignalUrl.indexOf("?") != -1) {
            domainUrl = orignalUrl.substring(0, orignalUrl.indexOf("?") + 1);
        }
        if (domainUrl.indexOf("?") == -1) { //是普通的字符串
            domainUrl = "";
        }
        var list = URLUtility.getUrlKeyValueArray(orignalUrl);
        if (list != null && list.length != 0) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].Key.toLowerCase() == key.toLowerCase()) {
                    list[i].Value = value;
                }
                domainUrl += list[i].Key + "=" + list[i].Value + "&";
            }
        }
        return domainUrl;
    },
    //获取 http://www.baidu.com
    GetFullDomain: function (url) {
        url = url || document.location.href;

        if (url.indexOf("?") > 0) {
            url = StringUtil.SearchValue(url, "http", "?", 2);
        }
        if (!StringUtil.endWith(url, "/")) {
            url += "/";
        }
        //http://wdfa.com/a/b/
        url = StringUtil.replaceAll(url, "//", "#abcdef#");
        url = StringUtil.SearchValue(url, "", "/");
        url = StringUtil.replaceAll(url, "#abcdef#", "//");
        return url;
    }
}
//倒计时
window.SetTimeCountdown = function (num, processFun, completeFun) {
    if (num > 0) {
        var tm = window.setInterval(function () {
            num--;
            if (num == 0) {
                window.clearInterval(tm);
                if (completeFun != undefined && completeFun != null) {
                    completeFun();
                }
            } else {
                if (processFun != undefined && processFun != null) {
                    processFun(num);
                }
            }
        }, 1000);
    }
}
//监控元素输入值变化 obj : eleId,timeSpan
window.MonitorInputChange = function (obj, callBack) {
    var Config = {
        timeSpan: 1
    };
    Config = $.extend(Config, obj, true);

    window.setInterval(function () {
        var MonitorId = Config.eleId;
        var WindowMonitorIdName = "WindowMonitorIdName" + MonitorId;
        var WindowMonitorRefreshTime = "WindowMonitorRefreshTime" + MonitorId;
        window[WindowMonitorIdName] = window[WindowMonitorIdName] || "";

        var nowValue = $.trim($('#' + MonitorId).val());
        if (window[WindowMonitorIdName] != nowValue) {
            window[WindowMonitorRefreshTime] = new Date(new Date().getTime() + 1000 * Config.timeSpan);
            window[WindowMonitorIdName] = nowValue;
        }

        if (new Date() >= new Date(window[WindowMonitorRefreshTime])) {
            window[WindowMonitorRefreshTime] = new Date(new Date().getTime() + 10000000 * 5);

            callBack && callBack();
        }
    }, 10);
}

window.DownLoadUrl = function (url) {
    //这个地址的页面，需要执行self.location.href=''文件地址
    var iframe;
    try {
        iframe = document.createElement('<iframe name="ifr" src="' + url + '"></iframe>');
    } catch (e) {
        iframe = document.createElement('iframe');
        iframe.name = 'ifr';
        iframe.src = url;
    }
    document.body.appendChild(iframe);
}
//浏览器
ExplorerUtility = {
    //Edge: 20  非IE：-1 
    IEVersion: function () {
        try {

            var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
            var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
            var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
            var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
            if (isIE) {
                var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
                reIE.test(userAgent);
                var fIEVersion = parseFloat(RegExp["$1"]);
                if (fIEVersion == 7) {
                    return 7;
                } else if (fIEVersion == 8) {
                    return 8;
                } else if (fIEVersion == 9) {
                    return 9;
                } else if (fIEVersion == 10) {
                    return 10;
                } else {
                    return 6; //IE版本<=7
                }
            } else if (isEdge) {
                return 20; //edge
            } else if (isIE11) {
                return 11; //IE11  
            } else {
                return -1; //不是ie浏览器
            }

        } catch (e) {

        }
        return -1; //不是ie浏览器
    },

    //获取浏览器类型
    getExplorerType: function () {
        /// <summary>
        /// 获取浏览器类型（返回字符描述：IE、Firefox）
        /// </summary>
        /// <returns></returns>
        var explorer = window.navigator.userAgent;
        if (explorer.indexOf("Firefox") >= 0) {
            return "Firefox";
        } else if (explorer.indexOf("Chrome") >= 0) {
            return "Chrome";
        } else if (explorer.indexOf("Opera") >= 0) {
            return "Opera";
        } else if (explorer.indexOf("Safari") >= 0) {
            return "Safari";
        } else if (explorer.indexOf("MSIE") >= 0 || explorer.indexOf("rv:11.0") >= 0) { //ie IE11特殊
            return "IE";
        } else {
            alert("Error未找到正确类型，用户代理字符串：" + explorer);
        }
        return "";
    },

    //设为首页 ，一般obj为this
    setHomePageUrl: function (obj, url) {
        try {
            obj.style.behavior = 'url(#default#homepage)';
            obj.setHomePage(url);
        } catch (e) {
            if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                } catch (e) {
                    alert('抱歉，此操作被浏览器拒绝！\n\n请在浏览器地址栏输入“about:config”并回车\n\n然后将[signed.applets.codebase_principal_support]的值设置为true，双击即可。');
                }
                var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                prefs.setCharPref('browser.startup.homepage', url);
            } else {
                alert('抱歉，您所使用的浏览器无法完成此操作。\n\n您需要手动将【' + url + '】设置为首页。');
            }
        }
    },

    //加入收藏
    addFavorite: function (title, url) {
        try {
            window.external.addFavorite(url, title);
        } catch (e) {
            try {
                window.sidebar.addPanel(title, url, "");
            } catch (e) {
                alert("抱歉，您所使用的浏览器无法完成此操作。\n\n加入收藏失败，请使用Ctrl+D进行添加");
            }
        }
    },

    //禁用浏览器后退按钮
    DisableBackAway: function () {
        var counter = 0;
        if (window.history && window.history.pushState) {
            $(window).on('popstate', function () {
                window.history.pushState('forward', null, '#');
                window.history.forward(1);
            });
        }
        window.history.pushState('forward', null, '#'); //在IE中必须得有这两行
        window.history.forward(1);

        var str = '';
        str += '<meta http-equiv="Cache-Control" content="no-cache,no-store, must-revalidate" />';
        str += '<meta http-equiv="pragma" content="no-cache" />';
        str += '<meta http-equiv="expires" content="0" />';

        $("head").append(str);
    },
}
//层级关系Tree
var TreeUtl = {
    Config: {},
    //treeDataAry 数组  ，pkid:主键，parId,上级  rootidParValue:根节点的上级节点 Name:名字属性
    //idrename id别名  namerename name别名   chilsrename 子节点别名
    CrateTree: function (treeDataAry, pkid, parid, rootidParValue, Name, idrename, namerename, chilsrename) {
        if (treeDataAry == null || treeDataAry.length == 0) return [];
        this.Config.Arry = treeDataAry;
        this.Config.pkid = pkid;
        this.Config.parid = parid;
        this.Config.rootidParValue = rootidParValue;
        this.Config.Name = Name;

        this.Config.IdName = idrename ? idrename : "id";
        this.Config.FullName = namerename ? namerename : "name";
        this.Config.ChildsName = chilsrename ? chilsrename : "childs";

        var ele = ArrayUtility.SingleOrDefault(this.Config.Arry, function (a) { return a[parid] == rootidParValue });
        var Root = ele;
        Root[this.Config.IdName] = ele[pkid];
        Root[this.Config.FullName] = ele[Name];
        Root[this.Config.ChildsName] = [];

        this.PushChilds(this.Config.Arry, Root);
        console.log(Root);
        return Root;
    },
    PushChilds: function (arr, ParNode) {
        var chils = this.GetChilds(arr, ParNode[this.Config.pkid]);
        if (chils.length == 0) {
            delete ParNode[this.Config.ChildsName];
        }
        for (var i = 0; i < chils.length; i++) {
            var eleIn = chils[i];
            var objInner = eleIn;
            objInner[this.Config.IdName] = eleIn[this.Config.pkid];
            objInner[this.Config.FullName] = eleIn[this.Config.Name];
            objInner[this.Config.ChildsName] = [];

            ParNode[this.Config.ChildsName].push(objInner);
            this.PushChilds(arr, objInner);
        }
    },
    GetChilds: function (arr, parid) {
        var parIdName = this.Config.parid;
        return ArrayUtility.Where(arr, function (a) { return a[parIdName] == parid });
    }
}
Valid = {
    IsEmail: function (value) {
        /// <summary>
        ///检验是否是Emal类型
        ///</summary>
        ///<param name="value">待校验数据</param>
        if ($.trim(value).length == 0) {
            return false;
        }
        value = $.trim(value);
        var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        return reg.test(value);
    },

    IsMobile: function (value) {
        /// <summary>
        ///检验是否是手机号码
        ///</summary>
        ///<param name="value">待校验数据</param>
        if ($.trim(value).length == 0) {
            return false;
        }
        if ($.trim(value).length != 11) {
            return false;
        }
        value = $.trim(value);
        var reg = /^1[3|5|7|8|9][0-9]\d{4,8}$/;
        return reg.test(value);
    },

    IsPostCode: function (value) {
        /// <summary>
        ///检验是否是邮编类型
        ///</summary>
        ///<param name="value">待校验数据</param>
        if ($.trim(value).length == 0) {
            return false;
        }
        value = $.trim(value);
        var reg = /[1-9]\d{5}(?!\d)/;
        return reg.test(value);
    },

    //身份证
    IsIDNumber: function (value) {
        /// <summary>
        ///检验是否是身份证类型
        ///</summary>
        ///<param name="value">待校验数据</param>
        if ($.trim(value).length == 0) {
            return false;
        }
        value = $.trim(value);
        var reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
        return reg.test(value);
    },

    IsInt32: function (value, canEmpty) {
        /// <summary>
        ///检验是否是Int32类型
        ///</summary>
        ///<param name="value">待校验数据</param>
        if ($.trim(value).length == 0) {
            if (canEmpty != undefined) {
                return false;
            }
            return false;
        }
        value = $.trim(value);
        var reg = /^-?\d+$/;
        var r = reg.test(value);
        if (r) {
            max = parseInt(value);
            if (max <= 2147483647 && max >= -2147483648) { //需要在Int32的范围之内
                return true;
            }
        }
        return false;
    },

    IsFloat: function (theFloat) {
        var isFloat = false
        //判断是否为浮点数 
        len = theFloat.length;
        dotNum = 0;
        if (len == 0) isFloat = true;
        for (var i = 0; i < len; i++) {
            oneNum = theFloat.substring(i, i + 1);
            if (oneNum == ".") dotNum++;
            if (((oneNum < "0" || oneNum > "9") && oneNum != ".") || dotNum > 1) isFloat = true;
        }
        if (len > 1 && theFloat.substring(0, 1) == "0") {
            if (theFloat.substring(1, 2) != ".") isFloat = true;
        }
        return !isFloat;
    },

    IsDateTime: function (value) {
        /// <summary>
        ///检验是否是日期类型
        ///</summary>
        ///<param name="value">待校验数据</param>
        var d = new Date(value);
        return isNaN(d.getFullYear()) == false;
    },

    //是否是正确的车牌号
    isVehicleNumber: function (vehicleNumber) {
        vehicleNumber = $.trim(vehicleNumber);
        vehicleNumber = vehicleNumber.toUpperCase();
        if ($.String.startWith(vehicleNumber, "鲁") == false) {
            return false;
        }
        var result = false;
        if (vehicleNumber.length == 7) {
            var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
            result = express.test(vehicleNumber);
        }
        return result;
    },
    //是否包含中文
    IsContainChina: function (value) {
        if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
            return true;
        }
        return false;
    },
}

//DOM
SelectDom = {
    //选择元素
    GetSelectDom: function (id) {
        var dom = $('#' + id);
        if (dom.length == 0) {
            dom = $("select[name='" + id + "']");
        }
        return dom;
    },
    //清空选项
    RemoveAllOption: function (id) {
        $(SelectDom.GetSelectDom(id)).empty();
    },
    //删除选项  type:index 、text、value
    RemoveOption: function (id, value, type) {
        var option = null;
        switch (type) {
            case "index":
                option = SelectDom.GetOptionByIndex(id, value);
                break;
            case "text":
                option = SelectDom.GetOptionByText(id, value);
                break;
            case "value":
                option = SelectDom.GetOptionByValue(id, value);
                break;
            default:
        }
        if (option != null) {
            option.remove();
        } else {
            console.log("删除Option失败，id：" + id + " value:" + value + "type:" + type);
        }
    },
    //添加选项 isFirst true:首位
    AppendOption: function (id, name, value, isFirst) {
        var first = isFirst == undefined ? true : isFirst;
        first = first && isFirst;
        var dom = SelectDom.GetSelectDom(id);
        var optionStr = "<option value='" + value + "'>" + $.trim(name) + "</option>";
        if (first) {
            dom.prepend(optionStr);
        } else {
            dom.append(optionStr);
        }
    },
    //获取选中文本
    GetSelectedText: function (id) {
        var text = SelectDom.GetSelectDom(id).find("option:selected").text();
        return text;
    },
    //获取选中值
    GetSelectedValue: function (id) {
        var va = SelectDom.GetSelectDom(id).val();
        return va;
    },
    //获取选中索引
    GetSelectedIndex: function (id) {
        var va = SelectDom.GetSelectDom(id).get(0).selectedIndex;
        return va;
    },
    //设置选中索引
    SetSelectedIndex: function (id, index) {
        SelectDom.GetSelectDom(id).get(0).selectedIndex = index;
    },
    //设置选中文本返回值
    SetSelectedText: function (id, text) {
        var count = 0;
        var value = '';
        SelectDom.GetSelectDom(id).find("option").each(function () {
            if ($(this).html() == text) {
                SelectDom.GetSelectDom(id).get(0).selectedIndex = count;
                value = $(this).val();
            }
            count++;

        });
        if (count > 1) {
            console.log(id + "存在多个相同的Text：" + text);
        }
        return value;
    },
    //设置选中值
    SetSelectedValue: function (id, value) {
        var va = SelectDom.GetSelectDom(id).val(value);
        return va;
    },
    //修改选中的项
    ModifySelectdOption: function (id, name, value, mindex) {
        var index = mindex || SelectDom.GetSelectedIndex(id);
        SelectDom.GetSelectDom(id)[0].options[index] = new Option(name, value);
        SelectDom.SetSelectedIndex(id, index);
    },

    ///获取项目 type:index、text、value
    GetOption: function (id, value, type) {
        var option = null;
        if (type == 'index') {
            option = SelectDom.GetSelectDom(id).find('option')[value];
        } else {
            SelectDom.GetSelectDom(id).find("option").each(function () {
                if ($(this).html() == value && type == 'text') {
                    option = $(this);
                    return false;
                }
                if ($(this).val() == value && type == 'value') {
                    option = $(this);
                    return false;
                }
            });
        }
        if (option != null) {
            return option;
        }
        console.log("查找Option失败，id：" + id + " value:" + value + "type:" + type);
    },
    GetOptionByText: function (id, text) {
        return SelectDom.GetOption(id, text, 'text');
    },
    GetOptionByValue: function (id, value) {
        return SelectDom.GetOption(id, value, 'value');
    },
    GetOptionByIndex: function (id, index) {
        return SelectDom.GetOption(id, index, 'index');
    },

    Bind: function (id, arry, text, value) {
        SelectDom.RemoveAllOption(id);
        if (arry != null && arry.Length != 0) {
            for (var i = 0; i < arry.length; i++) {
                var obj = arry[i];
                var text1 = ObjectUtility.getPropertyValue(obj, text);
                var value1 = ObjectUtility.getPropertyValue(obj, value);
                SelectDom.AppendOption(id, text1, value1, false);
            }
        }
    }
}

$.extend({
    Page: {
        //ID>Name>Class
        getEleValue: function (id, findType) {
            var c = $.Page.getEle(id, findType);
            if (c == null || c.length == 0) {
                return null;
            } else {
                //找到元素后进行复制操作
                var tagName = $(c)[0].tagName.toLowerCase();
                var type = ($(c).attr("type") || "").toLowerCase();

                switch (tagName) {
                    case "input":
                        if (type == "checkbox" || type == "radio") {
                            val = $(c).is(':checked');
                        } else {
                            val = $(c).val();
                        }
                        break;
                    case "select":
                        val = $(c).val();
                        break;
                    case "textarea":
                        val = $(c).val();
                        break;
                    default:
                        val = $(c).val();
                }
            }

            return val;
        },

        //ID>Name>Class
        setEleValue: function (id, value, findType) {
            var c = $.Page.getEle(id, findType);
            if (c == null || c.length == 0) { } else {
                //找到元素后进行复制操作
                var tagName = $(c)[0].tagName.toLowerCase();
                var type = ($(c).attr("type") || "").toLowerCase();

                var inputArry = ['date', 'datetime', 'datetime-local',
                    'email', 'month', 'number', 'range', 'search',
                    'tel', 'time', 'url', 'week', 'hidden'
                ];
                var notInputArry = ['button', 'submit', 'file', 'image', 'color'];

                if (notInputArry.indexOf(tagName) == -1) {
                    switch (tagName) {
                        case "input":
                            if (type == null || type == undefined || type == "" || type == "text" || type == "hidden" || (inputArry.indexOf(tagName) != -1)) {
                                $(c).val(value);
                            } else if (type == "checkbox" || type == "radio") {
                                if (value == true || value == "True" || value == "true" || value == 1 || value == "1") {
                                    $(c).attr("checked", true);
                                } else {
                                    $(c).attr("checked", false);
                                }
                            }
                            break;
                        case "select":
                            if ($(c).find("option[value='" + value + "']").length > 0) {
                                $(c).val(value);
                            } else {
                                $(c).find("option").each(function () {
                                    if (this.text == value) {
                                        $(this).attr("selected", true);
                                    }
                                });
                            }
                            break;
                        case "textarea":
                            $(c).val(value);
                            break;
                        default:
                    }
                }
                console.log(tagName + "  |" + type);
            }
        },

        //根据ID查找 元素
        getEleById: function (id) {
            if (id == null || $.trim(id) == "") {
                return null;
            }
            var c = $("#" + id);
            if (c.length == 0) {
                c = $("*[id$='" + id + "']");
                if (c.length == 0) {
                    c = $("*[id^='" + id + "']");
                    if (c.length == 0) {
                        c = $("*[id*='" + id + "']");
                        if (c.length == 0) {
                            return null;
                        }
                    }
                }
            }
            return c;
        },

        //根据Name查找
        getEleByName: function (id) {
            if (id == null || $.trim(id) == "") {
                return null;
            }
            var c = $("*[name='" + id + "']");
            if (c.length == 0) {
                c = $("*[name$='" + id + "']");
                if (c.length == 0) {
                    c = $("*[name^='" + id + "']");
                    if (c.length == 0) {
                        c = $("*[name*='" + id + "']");
                        if (c.length == 0) {
                            return null;
                        }
                    }
                }
            }
            return c;
        },

        //ID>Name>Class 获取元素
        getEle: function (id, findType) {
            var c = null;
            var val; //返回的值
            if (findType == undefined) {
                c = $("#" + id);
                if (c.length == 0) {
                    c = $("*[name='" + id + "']");
                    if (c.length == 0) {
                        c = $("." + id);
                    }
                }
            } else if (findType == 'id') {
                c = $.Page.getEleById(id);
            } else if (findType == 'name') {
                c = $.Page.getEleByName(id);
            }
            if (c == null || c.length == 0) {
                return null;
            }
            return c;
        },

        //对对象进行序列化拼接
        getPostStr: function (obj) {
            //或者 $("#formId").serialize();
            if (typeof (obj) != "object") {
                console.log("getPostStr参数应为Object类型");
                return "";
            }
            var postStr = "";
            for (var p in obj) {
                if (typeof (obj[p]) == "function") {
                    continue;
                }
                postStr += p + "=" + encodeURIComponent(obj[p]) + "&";
            }
            postStr = postStr.substring(0, postStr.length - 1);
            return postStr;
        },

        ///根据ID列表获取post的字符串
        getPostStrByIdList: function (arry) {
            var obj = new Object();
            for (var i = 0; i < arry.length; i++) {
                obj[arry[i]] = $.Page.getEleValue(arry[i]);
            }
            var c = $.Page.getPostStr(obj);
            return c;
        },

        //序列化表单
        serialize: function (id) {
            return $.Page.getPostStr($.Page.getJsonObjByIdentity(id));
        },

        //用JSon对象给页面赋值  涉及轮询TODO 
        setJsonObj: function (obj) {
            var c = typeof (obj) == "string" ? $.parseJSON(obj) : obj;
            for (var i in c) {
                var val = c[i];
                if (StringUtil.startWith(val, '/Date(') && StringUtil.endWith(val, ')/')) {
                    val = $.Date.formatTime(val);
                    obj[i] = val;
                }
                $.Page.setEleValue(i, c[i]);
            }
        },

        //重置页面  涉及轮询TODO
        resetPage: function (formidentity, idList) {
            var x;
            if (idList == null || idList == undefined) {
                x = $.Page.getEle(formidentity);
                if (x != null && x != undefined) {
                    x = $(x).find('input,select,textarea');
                } else {
                    console.log(formidentity + " 为查找到元素！");
                }
            } else {
                x = idList;
            }
            var i = 0;
            $(x).each(function () {
                var identity = (idList == undefined || idList == null) ?
                    ($(this).attr("id") || $(this).attr("name") || $(this).attr("class") || "") :
                    (idList[i++]);
                if (identity != "") {
                    $.Page.setEleValue(identity, '');
                }
            });

        },


        //根据页面更新Model  涉及轮询TODO
        updateModelByPage: function (tarObj, formidentity, idList) {
            var obj = $.Page.getJsonObjByIdentity(formidentity, idList);
            for (var i in obj) {
                try {
                    tarObj[i] = obj[i];
                } catch (e) {

                }
            }
        },


        //根据数组获取Json对象 涉及轮询TODO
        getJsonObjByIdentity: function (formidentity, idList) {
            var params = new Object();
            var x;
            if (idList == null || idList == undefined) {
                x = $.Page.getEle(formidentity);
                if (x != null && x != undefined) {
                    x = $(x).find('input,select,textarea');
                } else {
                    console.log(formidentity + " 未查找到元素！");
                }
            } else {
                x = idList;
            }
            var i = 0;
            $(x).each(function () {
                var identity = (idList == undefined || idList == null) ?
                    ($(this).attr("id") || $(this).attr("name") || $(this).attr("class") || "") :
                    (idList[i++]);
                if (identity != "") {
                    params[identity] = $.Page.getEleValue(identity);
                }
            });
            return params;
        },

        createRefreshButton: function () {
            var btnId = window.GetGuid();
            var btn = $("<input type='button' id='" + btnId + "' style=\"position: fixed !important;right: 10px;bottom: 10px;cursor: pointer;padding: 6px 12px;border: 1px solid transparent;border-radius: 4px;color: #fff;background-color: #47a447;\"  value='Refresh'>");
            $("body").append(btn);
            $("#" + btnId).click(function () {
                var url = $.Page.addOrUpdateUrlPara("refreshguid", window.GetGuid());
                location.href = url;
            });
        },
        createLoadingDiv: function () {
            var divLoading = '<div id="CusloadingCA517759E7BE">';
            divLoading += '       <div style="display: block; width: 100%; height: 100%; opacity: 0.3; filter: alpha(opacity=00); background: #808080; position: absolute; top: 0; left: 0; z-index: 100000;" id="loading_background"></div>';
            divLoading += '       <div style="color: #666; font-size: 20px; position: absolute; z-index: 100001; left: 40%; top: 40%; border: 1px solid rgb(187, 187, 187); width: auto; height: 80px; line-height: 78px; padding-left: 85px; padding-right: 20px; background: #fff; cursor: pointer; border-radius: 8px; background-image: url(/Images/Common/loading.gif); background-repeat: no-repeat; background-position: 8px 50%; box-shadow: 0 1px 15px rgba(0, 0, 0, .175); font-size: 12pt !important;"><span>正在加载中...</span></div>';
            divLoading += '   </div>';
            $("body").append(divLoading);
        },
        closeLoadingDiv: function () {
            $("#CusloadingCA517759E7BE").hide();
        },

        initEnterList: function (focusArrayList, isClickLast) { //默认true：click
            if (focusArrayList != undefined && focusArrayList.length > 1) {
                document.onkeydown = function (e) {
                    var keyCode = event.keyCode;
                    var currentId = document.activeElement.id;
                    if (keyCode && keyCode.toString() == "13") {
                        var currentIndex = $.inArray(currentId, focusArrayList);
                        if (currentIndex != -1) {
                            var nextIndex = currentIndex + 1;
                            if (nextIndex <= focusArrayList.length - 1) {
                                document.getElementById(focusArrayList[nextIndex]).focus();
                            }
                            if (nextIndex == focusArrayList.length - 1) {
                                if (isClickLast == undefined || isClickLast) {
                                    document.getElementById(focusArrayList[focusArrayList.length - 1]).click();
                                }
                            }
                        } else {
                            return false;
                            event.Cancel = true;
                        }
                    }
                };
            }
        },


        //打开页面 并POST值
        openPostForm: function (action, data, n) {
            /*调用举例
            var dataList = [
                    { "content": "这是内容部分" },
                    { "fromUrl": "http://www.baidu.com?" },
                ];
                MagicJSLib.openPostWindow("http://localhost:16672/WebForm1.aspx", dataList, "_blank");
                //取值 Request.Param["fromUrl"]
            */
            var form1 = document.createElement("form");
            form1.method = "POST";
            form1.target = n;
            if (n) {
                form1.target = n;
            };
            form1.action = action;
            document.body.appendChild(form1);

            for (var i = 0; i < data.length; i++) {
                var object = data[i];
                for (var property in object) {
                    // 创建一个输入 
                    var input = document.createElement("input");
                    // 设置相应参数 
                    input.type = "hidden";
                    input.name = property;
                    input.value = object[property];
                    // 将该输入框插入到 form 中 
                    form1.appendChild(input);
                }
            }

            form1.submit();
            document.body.removeChild(form1);
        }

    }
});

/*扩展类库*/
//提示框
var Msg = {
    AlertWarm: function (msg, fun) {
        top.layer.alert(msg, {
            icon: 2,
            closeBtn: 0
        }, fun);
    },
    AlertTip: function (msg) {
        layer.msg(msg)
    },
    ShowAndRedirect: function (msg, url) {
        layer.msg(msg);
        setTimeout(function () {
            location.href = url;
        }, 2000);
    },
    ShowAndContinue: function (msg, cb) {
        layer.msg(msg);
        setTimeout(function () {
            cb();
        }, 2000);
    },
    Alert: function (msg, fun) {
        top.layer.alert(msg, {
            icon: 1,
            closeBtn: 0
        }, fun);
    },
    Confirm: function (msg, sureFun, cancelFun) {
        top.layer.confirm(msg, {
            icon: 3,
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            top.layer.close(index);
            if (sureFun) {
                sureFun();
            }

        }, function () {
            if (cancelFun) {
                cancelFun();
            }

        });
    },
    Prompt: function (title, sureFun) {
        top.layer.prompt({
            formType: 2, //1：单行文本 2：多行文本
            title: title,
            area: ['500px', '60px']
        }, function (value, index, elem) {
            layer.close(index);
            sureFun(value);
        });
    },
    //加载中，动画  layer.closeAll()
    Loading: function (msg) {
        var tip = msg || "加载中....";
        layer.msg(tip, {
            icon: 16,
            time: -1
        });
    }

    //加载动画 1 2 3
    // let index= layer.load(4);layer.close(index);
}

var BootStrapFileUpload = {
    configList: [],
    //配置
    Init: function (config) {
        this.configList.push(config);
        var str = '';
        str += '<button type="button" id="btn' + config.id + '" style="margin-left: 3px;" class="btn btn-primary btn-xs" onclick="document.getElementById(\'' + config.id + 'File\').click();" >选择文件</button>';
        str += '<input  type="file" id="' + config.id + 'File" style="display:none" onchange="BootStrapFileUpload.UploadFile(\'' + config.id + '\')"/>';
        str += '';
        if ($("#" + "btn" + config.id).length == 0) {
            $('#' + config.id).after(str);
        }

    },

    //上传文件和成功后回调
    UploadFile: function (Id) {
        var config = this.GetConfigById(Id);
        var fId = config.id;
        var formData = new FormData();
        formData.append("imgFile", document.getElementById(fId + "File").files[0]);
        $.ajax({
            url: FileServer,
            dataType: 'json',
            type: 'POST',
            async: true,
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                if ('string' == typeof (data)) {
                    data = JSON.parse(data);
                }
                if (data.isOk) {
                    var fileId = data.att.id;
                    var fileName = data.att.name;
                    var filePath = data.att.path;
                    $("#" + config.id).val(fileId);
                    var str = '';
                    str += '<a id="View_' + config.id + '" href="' + filePath + '" target="_blank" style=" width: 150px;height:15px;line-height:15px; ">' + fileName + '</a>';
                    if ($("#" + "View_" + config.id).length != 0) {
                        $("#" + "View_" + config.id).attr('href', filePath).html(fileName);
                    } else {
                        $('#' + config.id).after(str);
                    }

                    if ($("#" + "Clear" + config.id).length == 0) {
                        var str = '';
                        str += '<button type="button" class="btn btn btn-danger btn-xs" id="Clear' + config.id + '" onclick="BootStrapFileUpload.Clear(\'' + config.id + '\')" style="margin-left: 3px;"><i class="fa fa-remove"></i>删除</button>';
                        $("#" + config.id + "File").before(str);
                    }

                    if (config.successFun) {
                        config.successFun(data);
                    }
                } else {
                    alert(data.msg);
                }


            },
            error: function (response) {
                alert(response);
            }
        });
    },
    Clear: function (id) {
        var config = this.GetConfigById(id);
        var imgId = "View_" + config.id;
        var DId = "Clear" + config.id;
        document.getElementById(imgId).remove();
        document.getElementById(DId).remove();
        if (config.DeleteFun) {
            config.DeleteFun(config.id);
        }
    },
    //获取配置文件
    GetConfigById: function (id) {
        for (var i = 0; i < this.configList.length; i++) {
            var obj = this.configList[i];
            if (obj.id == id) {
                return obj;
            }
        }
        return null;
    }
}
/*
 1.初始化 在展示位置展示两个Hidden Input <input hidden name="Att" id="Att" /> <input hidden name="AttName" id="AttName" />
 然后初始化 BootStrapFileSelfUpload.Init({ id: "Att" ,dirName:'NewsAtt'}); 指明保存位置
 2.赋值  BootStrapFileSelfUpload.InitFileSet("Att", app.pageEle.AttName, app.pageEle.Att);
 3.取值 $('#Att').val()  $('#AttName').val()
 4.禁用修改   BootStrapFileSelfUpload.DisableEdit('Att')
 */
var BootStrapFileSelfUpload = {
    configList: [],
    //初始化上传配置
    Init: function (config) {
        this.configList.push(config);
        //初始化时就显示选择文件的按钮
        var str = '';
        str += '<button type="button" id="btn' + config.id + '" style="margin-left: 3px;" class="btn btn-primary btn-xs" onclick="document.getElementById(\'' + config.id + 'File\').click();" >选择文件</button>';
        str += '<input  type="file" id="' + config.id + 'File" style="display:none" onchange="BootStrapFileSelfUpload.UploadFile(\'' + config.id + '\')"/>';
        str += '';
        if ($("#" + "btn" + config.id).length == 0) {
            $('#' + config.id).after(str);
        }
    },

    //上传文件和成功后回调
    UploadFile: function (Id) {
        var config = this.GetConfigById(Id);
        var fId = config.id;
        if (config.dirName == undefined) {
            config.dirName = "";
        }
        var formData = new FormData();
        formData.append("imgFile", document.getElementById(fId + "File").files[0]);
        $.ajax({
            url: '/Common/UploadSummerImg?dirName=' + config.dirName + "&rd=" + Math.random(),
            dataType: 'json',
            type: 'POST',
            async: true,
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                if ('string' == typeof (data)) {
                    data = JSON.parse(data);
                }
                if (data.ok) {
                    var fileName = data.fileName;
                    var filePath = data.url;
                    $("#" + config.id).val(filePath);
                    $("#" + config.id + 'Name').val(fileName);

                    //出现选择的文件预览框，如果已经有了就更新ID
                    var str = '';
                    str += '<a id="View_' + config.id + '" href="' + filePath + '" target="_blank" style=" width: 150px;height:15px;line-height:15px; ">' + fileName + '</a>';
                    if ($("#" + "View_" + config.id).length != 0) {
                        $("#" + "View_" + config.id).attr('href', filePath).html(fileName);
                    } else {
                        $('#' + config.id).before(str);
                    }

                    //加入清除按钮
                    if ($("#" + "Clear" + config.id).length == 0) {
                        var str = BootStrapFileSelfUpload.getClearBtn(config.id);
                        $("#" + config.id + "File").before(str);
                    }

                    if (config.successFun) {
                        config.successFun(data);
                    }
                } else {
                    alert(data.msg);
                }


            },
            error: function (response) {
                alert(response);
            }
        });
    },

    Clear: function (id) {
        var config = this.GetConfigById(id);
        var imgId = "View_" + config.id;
        var DId = "Clear" + config.id;
        document.getElementById(imgId).remove();
        document.getElementById(DId).remove();
        $('#' + config.id).val('');
        $('#' + config.id + "Name").val('');
        if (config.DeleteFun) {
            config.DeleteFun(config.id);
        }
    },

    //获取配置文件
    GetConfigById: function (id) {
        for (var i = 0; i < this.configList.length; i++) {
            var obj = this.configList[i];
            if (obj.id == id) {
                return obj;
            }
        }
        return null;
    },
    //文件赋值
    InitFileSet: function (EleId, Name, Path) {
        if (Name != null) {
            var str = BootStrapFileSelfUpload.getViewBtn(EleId, Path, Name);
            $('#' + EleId).before(str);
            $('#' + EleId).val(Path);
            $('#' + EleId + 'Name').val(Name);

            var ClearBtn = BootStrapFileSelfUpload.getClearBtn(EleId);
            $('#btn' + EleId).after(ClearBtn);
        }
    },
    DisableEdit: function (id) {
        $('#Clear' + id).remove();
        $('#btn' + id).remove();
    },

    //获取清除按钮Html
    getClearBtn: function (id) {
        var str = '<button type="button" class="btn btn btn-danger btn-xs" id="Clear' + id + '" onclick="BootStrapFileSelfUpload.Clear(\'' + id + '\')" style="margin-left: 3px;"><i class="fa fa-remove"></i>删除</button>';
        return str;
    },
    //获取文件的预览按钮Html
    getViewBtn: function (EleId, Path, Name) {
        var str = '<a id="View_' + EleId + '" href="' + Path + '" target="_blank" style="width: 150px; height: 15px; line-height: 15px;">' + Name + '</a>';
        return str;
    }
}

//获取字典
function GetDictsByCode(code, valueTag) {
    var list = ArrayUtility.Where(JSON.parse(localStorage.getItem('AllDict')), function (d) { return d.Type == code; });
    var dlist = list.map(item => {
        return {
            Id: (valueTag == undefined ? parseInt(item.Id) : item[valueTag]),
            Text: item.Text,
        };
    });
    return dlist;
}

//获取字典
function GetDictsByParId(ParId) {
    var list = ArrayUtility.Where(JSON.parse(localStorage.getItem('AllDict')), function (d) { return d.ParId == ParId; });
    var dlist = list.map(item => {
        return {
            Id: parseInt(item.Id),
            Text: item.Text,
        };
    });
    var rlist = ArrayUtility.Distinct(dlist);
    return rlist;
}
//获取难度描述
function GetNanDu(id) {
    var str = ''
    if (id == 1) {
        str = "一般"
    } else if (id == 2) {
        str = "简单"
    } else if (id == 3) {
        str = "困难"
    } else {
        str = "未知"
    }
    return str;
}
function GetNanDuAry() {
    var ary = [{
        id: 1,
        name: "一般"
    }, {
        id: 2,
        name: "简单"
    }, {
        id: 3,
        name: "困难"
    }];
    return ary;
}
//试题分类描述
function GetShiTiTypeDes(Id) {
    var list = GetDictsByCode('ShiTiTypes', 'ValueTag');
    var obj = ArrayUtility.SingleOrDefault(list, function (d) { return d.Id.toString() == Id.toString() });
    if (obj != null) {
        return obj.Text;
    }
    return '';
}
